<div class="layuimini-container layuimini-page-anim">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">编号</label>
                            <div class="layui-input-inline">
                                <input type="text" name="id" autocomplete="off" class="layui-input">
                            </div>
                        </div>

                        <div class="layui-inline">
                            <label class="layui-form-label">是否占用</label>
                            <div class="layui-input-inline">
                                <input type="text" name="isOccupied" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">所在区域</label>
                            <div class="layui-input-inline">
                                <input type="text" name="region" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加 </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除 </button>
                <button class="layui-btn layui-btn-sm layui-btn" lay-event="export"> 导出 </button>
                <button class="layui-btn layui-btn-sm layui-btn layui-btn-normal" lay-event="import"> 导入 </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>
        <script type="text/html" id="ImportExcel">
            <div class="layui-form-block">
                <input type="file" class="layui-btn layui-btn-sm layui-btn-normal" id="LAY-excel-import-excel"
                       multiple="multiple">
            </div>
        </script>
    </div>
</div>

<script>
    layui.use(['form', 'table', 'miniPage', 'element','excel'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            excel = layui.excel,
            miniPage = layui.miniPage;



        //渲染表格
        table.render({
            elem: '#currentTableId',
            url: 'api/Park/GetParksByPage',
            parseData: function (res) { //res 即为原始返回的数据
                return {

                    "code": res.code === 200 ? 0 : res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.result, //解析数据长度
                    "data": res.data //解析数据列表
                }
            },
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                { type: "checkbox", width: 80, align: "center" },
                { field: 'id', width: 100, title: 'ID', sort: true, align: "center" },
                {
                    field: 'isOccupied', width: 120, align: "center", title: '是否被占用', templet: function (res) {
                        var menuId = res.id;
                        if (res.isOccupied) {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "' lay-filter='Occupied' lay-skin='switch' lay-text='Y|N' checked>";
                        } else {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "'  lay-filter='Occupied' lay-skin='switch' lay-text='Y|N'>";
                        }
                    }
                },
                {
                    field: 'enable', width: 120, align: "center", title: '禁/启用', templet: function (res) {
                        var menuId = res.id;
                        if (res.enable) {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "' lay-filter='state' lay-skin='switch' lay-text='ON|OFF' checked>";
                        } else {
                            return "   <input type='checkbox'  menuId = '" +
                                menuId +
                                "'  lay-filter='state' lay-skin='switch' lay-text='ON|OFF'>";
                        }
                    }
                },
                { field: 'region', width: 140, title: '区域', align: "center" },
                { field: 'xPosition', width: 120, title: 'X坐标', align: "center" },
                { field: 'yPosition', width: 120, title: 'Y坐标', align: "center" },
                { field: 'floor', title: '所在楼层', width: 120, align: "center" },
                { title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center" }
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: true,
            id: 'reloadTable',
            even: "true",
            skin: 'row'

        });

        //表格重新加载
        var tablereload = function (search) {
            table.reload('reloadTable',
                {
                    where: {
                        query: search
                    }, page: {
                        curr: 1
                    }
                });
        }


        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {

            var query = {};
            for (var key in data.field) {
                if (data.field[key].length > 0) {
                    query[key] = data.field[key];
                }
            };
            tablereload(JSON.stringify(query));
            return false;
        });


        //启用禁用
        form.on('switch(Occupied)', function (data) {
           
            var id = data.elem.attributes['menuId'].nodeValue;
            var enable = data.elem.checked;
            var msg = enable ? "启用" : "禁用";
            $.ajax({
                url: 'api/Park/Occupied/' + id + "/" + enable,
                method: 'patch',
                contentType: 'application/json',
                cache: false,
                success: function (res) {
                    layer.msg(msg + '成功!', { icon: 1 });
                },
                error: function (data) {
                    layer.msg(msg + '失败!', { icon: 2 });
                }
            });

        });
        //启用禁用
        form.on('switch(state)', function (data) {

            var id = data.elem.attributes['menuId'].nodeValue;
            var enable = data.elem.checked;
            var msg = enable ? "启用" : "禁用";
            $.ajax({
                url: 'api/Park/Enable/' + id + "/" + enable,
                method: 'patch',
                contentType: 'application/json',
                cache: false,
                success: function (res) {
                    layer.msg(msg + '成功!', { icon: 1 });
                },
                error: function (data) {
                    layer.msg(msg + '失败!', { icon: 2 });
                }
            });

        });

        //监听 toolbar添加删除
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {   // 监听添加操作
                var content = miniPage.getHrefContent('page/Park/AddPark.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '添加Park点',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    end: function (index, layero) {
                        tablereload("");
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            }
            else if (obj.event === 'delete') {  // 监听删除操作
                // 监听删除操作
                var checkStatus = table.checkStatus('reloadTable')
                    , data = checkStatus.data;
                layer.close(index);

                var ids = [];
                data.forEach(x => { ids.push(x.id); });
                console.log(JSON.stringify(ids));
                $.ajax({
                    url: 'api/Park/DeleteByIds',
                    method: 'delete',
                    contentType: 'application/json;charset=UTF-8',
                    cache: false,
                    data: JSON.stringify(ids),
                    success: function (res) {
                        if (res.code === 200) {
                            layer.msg('删除成功!', { icon: 1 },
                                function () {
                                    tablereload("");
                                });
                        } else
                            layer.msg('删除失败!', { icon: 2 });
                    },
                    error: function (data) {

                        layer.msg('删除出错!', { icon: 2 });

                    }
                });
            }
            else if (obj.event === 'export') {
                debugger;
                var data = table.cache.reloadTable
                data = excel.filterExportData(data, [
                    'id'
                    , 'isOccupied'
                    , 'enable'
                    , 'region'
                    , 'xPosition'
                    , 'yPosition'
                ]);
                data.unshift({ id: "ID", isOccupied: '是否占用', enable: '禁/启用', region: '区域', xPosition: 'X坐标', yPosition: 'Y坐标' });
                excel.exportExcel(data, '停车点信息.xlsx', 'xlsx');
            }
            else if (obj.event === 'import') {
                var index = layer.open({
                    title: '导入数据',
                    type: 1,
                    shade: 0.2,

                    area: ['250px', '180px'],

                    content: $('#ImportExcel').html(),
                    success: function (layero, index) {
                        // 监听上传文件的事件
                        $('#LAY-excel-import-excel').change(function (e) {
                            var files = e.target.files;
                            try {
                                // 方式一：先读取数据，后梳理数据
                                excel.importExcel(files, {}, function (data) {

                                    data = excel.filterImportData(data, {
                                        'id': 'A'
                                        , 'isOccupied': 'B'
                                        , 'enable': 'C'
                                        , 'region': 'D'
                                        , 'xPosition': 'E'
                                        , 'yPosition': 'F'
                                    })

                                    data = data['0']['sheet1']
                                    data = data.splice(1, data.length - 1)
                                    $.ajax({
                                        url: '/api/Park/Import',
                                        method: 'post',
                                        contentType: 'application/json',
                                        cache: false,
                                        data: JSON.stringify(data),
                                        success: function (res) {

                                            layer.msg('导入成功!', { icon: 1 });
                                            layer.close(index);
                                        },
                                        error: function (data) {

                                            layer.msg('导入失败!', { icon: 2 });
                                            layer.close(index);

                                        }
                                    });

                                });

                            }
                            catch (e) {
                                layer.alert(e.message);
                            }
                        })

                    },
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    end: function (index, layero) {
                        layer.close(index);
                        //修改成功后刷新父界面
                        tablereload("");
                    }
                });
            }
        });

      

        //监听操作框事件
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                var content = miniPage.getHrefContent('page/Park/EditPark.html');
                var openWH = miniPage.getOpenWidthHeight();

                var index = layer.open({
                    title: '编辑Park点',
                    type: 1,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [openWH[0] + 'px', openWH[1] + 'px'],
                    offset: [openWH[2] + 'px', openWH[3] + 'px'],
                    content: content,
                    success: function (layero, index) {

                        form.val("editParkForm",
                            {
                                "id": data.id,
                                "routeName": data.routeName,
                                "isOccupied": data.isOccupied,
                                "region": data.region,
                                "xPosition": data.xPosition,
                                "yPosition": data.yPosition,
                                "floor": data.floor,
                            });

                    }
                    //关闭弹出框的回调函数，不管弹出框是手动关闭还是通过脚本进行关闭，都执行
                    , end: function (index, layero) {
                        tablereload("");
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            }
            else if (obj.event === 'delete') {
                layer.confirm('您确定要删除吗?', function (index) {
                    var id = obj.data.id;
                    obj.del();
                    $.ajax({
                        method: 'delete',
                        contentType: 'application/json;charset=UTF-8',
                        cache: false,
                        url: 'api/Park/Delete/' + id,
                        success: function (res) {
                            if (res.code === 200) {
                                console.log(id);

                                layer.msg('删除成功!', { icon: 1 });
                            } else
                                layer.msg('删除失败!', { icon: 2 });
                        },
                        error: function (data) {
                            layer.msg('删除出错!', { icon: 2 });

                        }
                    });
                    layer.close(index);
                });
            }
           
        });

    });</script>